<?php
class AdminCmsCategoryForm extends VTNSCmsCategoryForm
{
	public function configure()
    {
		$this->setWidgets(array(
                'parent_id'	 	             	=> new sfWidgetFormChoice(array('choices' => $this->getCmsCategoryParent($this->getDefault("parent_id")))),
				'alias'                			=> new sfWidgetFormInput(),
                'name'                			=> new sfWidgetFormInput(),
				'position'						=> new sfWidgetFormInput()
				));
		$this->setValidators(array(
				'alias'			               	=>  new sfValidatorString(array('required' => "Bí danh chưa được nhập")),
	            'name'			               	=>  new sfValidatorString(array('required' => "Tên chưa được nhập")),
		));
        $this->widgetSchema->setNameFormat('cms_category[%s]');
		$this->widgetSchema->setLabels(array(
				'parent_id'						=> 'Mục cha',
				'alias'							=> 'Bí danh',
				'name'							=> 'Tên',
				'position'						=> 'Thứ tự'
		));
	}
	
	private function getCmsCategoryParent($cms_category_id)
	{
		$parents = array();
		$level = 0;
		$cms_category_id += 0;

		$c = Doctrine_Query::create()
			->select('c.*')
			->from('VTNSCmsCategory c')
			->where('c.parent_id = ?', 0)
			->orderBy('c.position');
		
		$results = $c->fetchArray();
		foreach ($results as $result)
		{
			if ($result['cms_category_id'] != $cms_category_id) {
				$str = "";
				
				if ($level > 0)
				{
					for($i=0;$i<$level;$i++)
					{
						$str .= " ";
					}
					$str .= "- ";
				}
				$parents[$result['cms_category_id']] = $str.$result['name'];
                $arr_temp = $this->getTreeCmsCategory($result['cms_category_id'], $level+2, $cms_category_id);
                if ($arr_temp)
				    $parents = $this->arr_merge($parents, $arr_temp);
                
			}
		}
        
		return $this->arr_merge(array(0=>'Không có mục cha'), $parents);
	}
	
	private function getTreeCmsCategory($parent_id, $level, $cms_category_id)
	{
		$parents = array();
		$c = Doctrine_Query::create()
			->from('VTNSCmsCategory c')
			->where('c.parent_id = ?', $parent_id)
			->orderBy('c.position');
		$results = $c->fetchArray();
		foreach ($results as $result)
		{
			if ($result['cms_category_id'] != $cms_category_id)
			{
				$str = "";
				
				if ($level > 0)
				{
					for($i=0;$i<$level;$i++)
					{
						$str .= "&nbsp;&nbsp;";
					}
					$str .= "- ";
				}
				$parents[$result['cms_category_id']] = $str.$result['name'];
                $arr_temp = $this->getTreeCmsCategory($result['cms_category_id'], $level+2, $cms_category_id);
                if ($arr_temp)
				    $parents = $this->arr_merge($parents, $arr_temp);
			}
		}
		return $parents;
	}
    
    private function arr_merge($arr1, $arr2)
    {
        foreach ($arr2 as $key => $value)
        {
            $arr1[$key] = $value;
        }
        return $arr1;
    }
}
?>